package controllers;

import java.util.Collection;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import services.AdministratorService;
import services.EventService;
import services.ParticipantService;
import services.RouteService;
import domain.Administrator;
import domain.Event;
import domain.Participant;
import domain.Registration;
import domain.Route;

@Controller
@RequestMapping("/route")
public class RouteController extends AbstractController {

	// Constructors -----------------------------------------------------------

	public RouteController() {
		super();
	}

	// Services ---------------------------------------------------------------

	@Autowired
	private RouteService routeService;

	@Autowired
	private EventService eventService;

	@Autowired
	private ParticipantService participantService;
	
	@Autowired
	private AdministratorService administratorService;

	// List events ------------------------------------------------------------

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView list(@RequestParam int eventId) {
		ModelAndView result;
		Collection<Route> routes;

		Event e = eventService.findOne(eventId);
		routes = routeService.findRoutesByEvent(e);
		boolean created = false;
		// Comprobar que el usuario este registrado para mostrar el enlace a
		// evaluar ruta
		Boolean registered = false;
		Collection<Registration> registrations = e.getRegistrations();
		for (Registration r : registrations) {
			Participant p;
			try {
				p = participantService.findByPrincipal();
			} catch (Exception ex) {
				p = null;
			}
			if (p != null && p == r.getParticipant()&& e.getFinishMoment().compareTo(new Date())<0) {
				registered = true;
			}
		}
		
		Administrator a;
		Date d = new Date();
		try{
			a = administratorService.findByPrincipal();
		} catch (Exception ex){
			a = null;
		}
		if(e.getAdministrator().equals(a)&&e.getStartMoment().compareTo(d)>0){
			created = true;
		}
		
		result = new ModelAndView("route/list");
		result.addObject("requestURI", "route/list.do");
		result.addObject("routes", routes);
		result.addObject("eventId", e.getId());
		result.addObject("registered", registered);
		result.addObject("created", created);
		if(e.getFinishMoment().compareTo(new Date())<0){
			result.addObject("elapsed",true );
		}
		return result;
	}
}
